package com.gameShare.service.user

import com.gameShare.enums.misc.ResponseCodeEnum
import com.gameShare.exceptions.BusinessException
import com.gameShare.mappers.user.UserLikeMapper
import com.gameShare.service.game.GameCommentService
import org.springframework.stereotype.Service

@Service
class UserCommentLikeService(
    private val userLikeMapper: UserLikeMapper,
    private val gameCommeService: GameCommentService
){

    /**
     * 用户点赞服务
     *
     * @param gameId 要点赞的游戏id
     * @param commentId 游戏下的评论id
     * @param userId
     * @return
     */
    // TODO 更新游戏的点赞数据
    fun like(gameId : String, commentId : Int, userId : String): Boolean {
        // 如果commentId不为空的话检查此游戏下是否包含此评论
        gameCommeService.checkCommentInGame(gameId, commentId)
        // 如果评论已经点赞则直接返回false
        if (checkUserLike(gameId, commentId, userId, 1))
            return false
        // 反则检查点赞记录是否存在，存在则更新激活状态，不存在则插入数据
        return (
            if (checkUserLike(gameId, commentId, userId, 0))
                userLikeMapper.updateActiveStatus(1, gameId, commentId, userId) == 1
            else
                userLikeMapper.insert(gameId, commentId, userId) == 1
        )
    }

    /**
     *
     * 取消点赞
     * @param gameId 游戏id
     * @param commentId 评论id
     * @param userId 用户id
     * @return
     */
    // TODO 更新游戏点赞数据
    fun cancelLike(gameId: String,commentId: Int, userId: String): Boolean {
        // 检查评论是否在该游戏下
        gameCommeService.checkCommentInGame(gameId, commentId)
        // 检查记录是否存在
        if (checkUserLike(gameId, commentId, userId, 1))
            // 存在则更新反则报错
           return userLikeMapper.updateActiveStatus(0, gameId, commentId, userId) == 1
        else
            throw BusinessException(ResponseCodeEnum.ARGUMENT_ERROR)
    }

    fun loadAllLikeCommentByGameId(gameId: String, userId: String): List<String> {
        return userLikeMapper.selectUserAllLikeCommentInGame(gameId, userId )
    }

    private fun checkUserLike(gameId : String, commentId : Int, userId : String, isActive : Int): Boolean {
        return userLikeMapper.checkUserLike(gameId,commentId, userId, isActive) == 1
    }
}